package cn.edu.nju.software.zp13.client.assignment4.xslt;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Templates;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

public class Transformer {
	private static TransformerFactory tf;

	static {
		tf = TransformerFactory.newInstance();
		tf.setAttribute("indent-number", 4);
	}

	/**
	 * generate new file via source xml file and xslt file.
	 * 
	 * @param	xmlFile source XML File.
	 * @param	xsltFile input XSLT File.
	 * @param	targetFile output File.
	 */
	public static void tansform(String xmlFile, String xsltFile, String targetFile) {
		Source xmlSource = new StreamSource(new File(xmlFile));
		Source xsltSource = new StreamSource(new File(xsltFile));
		try {
			//XSLT cached to memory to avoid loading it repeatfully.
			Templates cachedXSLT = tf.newTemplates(xsltSource);
			javax.xml.transform.Transformer  transformer = cachedXSLT.newTransformer();
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
			PrintWriter pw = new PrintWriter(new FileOutputStream(targetFile));
			StreamResult result = new StreamResult(pw);
			transformer.transform(xmlSource, result);
			System.out.println("File "+targetFile+" created successfully!");
		} catch (FileNotFoundException | TransformerException e) {
			e.printStackTrace();
		}
	}
	
	public static javax.xml.transform.Transformer wellFormatUtf8Transformer(){
		javax.xml.transform.Transformer transformer = null;
		try {
			transformer = tf.newTransformer();
		} catch (TransformerConfigurationException e) {
			e.printStackTrace();
		}
		transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		return transformer;
	}
}
